import apiClient from './client'
import type { CartItem, CartAddRequest, CartUpdateRequest, CartSummary } from '@/types'

export const cartService = {
  // ===== 购物车管理模块 (/api/v1/cart) =====

  // 添加商品到购物车
  addToCart: (itemData: { skuId: number; quantity: number }) =>
    apiClient.post<CartItem>('/api/v1/cart/add', undefined, {
      params: {
        skuId: itemData.skuId,
        quantity: itemData.quantity,
      },
    }),

  // 获取购物车列表
  getCartItems: () => apiClient.get<CartItem[]>('/api/v1/cart/list'),

  // 获取购物车商品数量
  getCartItemCount: () => apiClient.get<number>('/api/v1/cart/count'),

  // 获取购物车摘要
  getCartSummary: () => apiClient.get<CartSummary>('/api/v1/cart/summary'),

  // 更新购物车商品数量
  updateCartItem: (itemData: CartUpdateRequest) =>
    apiClient.post<CartItem>('/api/v1/cart/update-quantity', {
      cartId: itemData.cartId, // 与后端参数保持一致
      quantity: itemData.quantity,
    }),

  // 与计划对齐的更新接口（可供兼容使用）
  updateCart: (itemData: CartUpdateRequest) =>
    apiClient.post<CartItem>('/api/v1/cart/update', itemData),

  // 移除购物车商品
  removeFromCart: (cartItemId: number) =>
    apiClient.post('/api/v1/cart/remove', undefined, { params: { cartId: cartItemId } }), // 后端使用cartId参数

  // 批量移除购物车商品
  batchRemoveFromCart: (cartItemIds: number[]) =>
    apiClient.post('/api/v1/cart/remove-batch', { cartIds: cartItemIds }),

  // 清空购物车
  clearCart: () => apiClient.post('/api/v1/cart/clear'),

  // 选择购物车商品
  selectCartItem: (cartItemId: number, selected: boolean) =>
    apiClient.post('/api/v1/cart/update-selected', undefined, {
      params: { cartId: cartItemId, selected },
    }),

  // 全选/取消全选购物车商品
  selectAllCartItems: (selected: boolean) =>
    apiClient.post('/api/v1/cart/update-selected-all', undefined, { params: { selected } }),

  // 获取失效商品列表
  getInvalidItems: () => apiClient.get<CartItem[]>('/api/v1/cart/invalid'),
}

export default cartService
